package org.lex.jdbc.url.view;

import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.lex.jdbc.url.view.internal.JdbcConnectionTreeNode;
import org.lex.jdbc.url.view.internal.JdbcConnectionTreeNodeHelper;
import org.lex.swing.Swings;

public class JdbcConnectionTree extends JPanel {
	public static void main(String[] args) {
		Swings.show(new JdbcConnectionTree(new DefaultJdbcConnectionModel(
				new File("."))));
	}

	private JPanel controlPane;
	private JScrollPane scrollPane;
	private JTree tree;
	private DefaultTreeModel treeModel;
	private JButton btnNewDriver;

	private IJdbcConnectionModel model;
	private JdbcConnectionTreeNodeHelper helper = new JdbcConnectionTreeNodeHelper();

	/**
	 * Create the panel.
	 */
	public JdbcConnectionTree(IJdbcConnectionModel model) {
		this.model = model;
		initialize();
		try {
			this.setModel(model);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setModel(IJdbcConnectionModel model) throws IOException {
		this.model = model;
		JdbcConnectionTreeNode root = helper.createRootNode(model);
		this.getTreeModel().setRoot(root);
	}

	DefaultTreeModel getTreeModel() {
		if (null == treeModel) {
			DefaultMutableTreeNode root = new DefaultMutableTreeNode("");
			treeModel = new DefaultTreeModel(root);
		}
		return this.treeModel;
	}

	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		add(getControlPane(), BorderLayout.NORTH);
		add(getScrollPane(), BorderLayout.CENTER);
	}

	private JPanel getControlPane() {
		if (controlPane == null) {
			controlPane = new JPanel();
			controlPane.add(getBtnNewDriver());
		}
		return controlPane;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTree());
		}
		return scrollPane;
	}

	private JTree getTree() {
		if (tree == null) {
			tree = new JTree(this.getTreeModel());
		}
		return tree;
	}

	private JButton getBtnNewDriver() {
		if (btnNewDriver == null) {
			btnNewDriver = new JButton("New Driver");
		}
		return btnNewDriver;
	}
}
